import axios from 'axios'
import type { AxiosInstance } from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

// const baseURL: string = "https://ykcldd.guojutech.net/clglmanage/dev";
const baseURL: string = "http://172.18.10.34:15040"

const baseUploadUrl = `${baseURL}/manage/v1/storage/upload?dir=`

//上传图片
const uploadUrl = (fileId: string): string => `${baseUploadUrl}${fileId}`

interface ApiResult<T> {
  success: boolean
  code: number
  msg: string
  data: T
}

const request: AxiosInstance = axios.create({
  baseURL,
  timeout: 200000
})

// 添加请求拦截器
request.interceptors.request.use(
  (config) => {
    const xAuthToken: string | null = localStorage.getItem('x-auth-token')
    if (xAuthToken != null) {
      config.headers['x-auth-token'] = xAuthToken
    }
    return config
  },
  (error: any) => {
    // 处理请求错误
    return Promise.reject(error)
  }
)

// 添加响应拦截器
request.interceptors.response.use(
  (response) => {
    if (response.headers['x-auth-token']) {
      localStorage.setItem('x-auth-token', response.headers['x-auth-token'])
    }

    if (response?.data?.code === 401) {
      sessionStorage.removeItem('userStore')
      router.replace({ path: '/login', replace: true }).then()
    }
    return response
  },
  (error: any) => {
    ElMessage.error(error.message)
    return Promise.reject(error)
  }
)

 async function get<T>(url: string, params?: any, config?: any): Promise<ApiResult<T>> {
  const response = await request.get<ApiResult<T>>(url, { params, ...config })
  return response.data
}

 async function post<T>(url: string, data?: any, config?: any): Promise<ApiResult<T>> {
  const response = await request.post<ApiResult<T>>(url, data, config)
  return response.data
}
 async function fetchDelete<T>(
  url: string,
  params?: any,
  config?: any
): Promise<ApiResult<T>> {
  const response = await request.delete<ApiResult<T>>(url, {
    params,
    ...config
  })
  return response.data
}
 async function fetchPut<T>(url: string, data?: any, config?: any): Promise<ApiResult<T>> {
  const response = await request.put<ApiResult<T>>(url, data, config)
  return response.data
}

export {
  baseURL,
  uploadUrl,
  get,
  post,
  fetchDelete,
  fetchPut,
  type ApiResult,
}
